//
//  FixedIPViewController.m
//  Router
//
//  Created by gejiangs on 15/10/15.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "FixedIPViewController.h"
#import "DynamicIPViewController.h"
#import "ChooseWIFITypeView.h"
#import "BroadbandIPViewController.h"
#import "DiscoverHelper.h"
@interface FixedIPViewController ()<UITableViewDataSource,UITableViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *notButton;
@property (strong, nonatomic) UITableView *tableView;

@property (nonatomic, strong)   NSMutableArray *textArray;
@property (nonatomic, strong)   UIScrollView *scrollView;
@property (nonatomic, strong) ChooseWIFITypeView *wifiTypeView;
@property (nonatomic, strong) DiscoverHelper *discoverHelper;


@property (nonatomic, copy) NSString *ipAddress;
@property (nonatomic, copy) NSString *maskCode;
@property (nonatomic, copy) NSString *gateWay;
@property (nonatomic, copy) NSString *DNS;
@property (nonatomic, copy) NSString *DNSNote;

@end

@implementation FixedIPViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.discoverHelper = [[DiscoverHelper alloc] init];
    self.title = @"固定IP设置";
    
    [self initUI];
    //启用键盘
    [self enableKeyboardNotification];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];

}


-(void)initUI
{
    self.textArray = [NSMutableArray array];
    
    self.notButton.layer.borderColor = COLOR_BASE.CGColor;
    self.notButton.layer.borderWidth = 1.f;
    self.notButton.layer.cornerRadius = 5.f;
    self.nextButton.layer.cornerRadius = 5.f;
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:_scrollView];
    [_scrollView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    UIView *contentView = [UIView new];
    [_scrollView addSubview:contentView];
    [contentView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_scrollView);
        make.width.equalTo(_scrollView);
    }];
    
    //头部
    [contentView addSubview:self.topView];
    [_topView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.offset(180);
    }];
    
    //中间输入框
    UIView *boxView = [UIView new];
    boxView.layer.borderColor = COLOR_GRAY.CGColor;
    boxView.layer.borderWidth = 0.5f;
    boxView.layer.cornerRadius = 5.f;
    [contentView addSubview:boxView];
    [boxView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topView.bottom).offset(20);
        make.left.offset(25);
        make.right.offset(-25);
        make.height.offset(225);
    }];
    
    [boxView addSubview:self.tableView];
    [_tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    //按钮
    [contentView addSubview:self.nextButton];
    [_nextButton makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(boxView.bottom).offset(25);
        make.left.offset(25);
        make.right.offset(-25);
        make.height.offset(45);
    }];
    
    [contentView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_nextButton.bottom).offset(10);
    }];
}

#pragma mark 键盘事件
-(void)keyboardWillShowKeyHeight:(CGFloat)keyHeight
{
    [_scrollView updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-keyHeight);
    }];
}

-(void)keyboardWillHide
{
    [_scrollView updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
    }];
}

#pragma mark 按钮点击
- (IBAction)notButtonClicked:(id)sender
{
    __weak __typeof(self)weakSelf = self;
    [self.wifiTypeView setSelectedBlock:^(NSInteger index) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *vcs = [NSMutableArray arrayWithArray:strongSelf.navigationController.viewControllers];
        [vcs removeLastObject];
        BaseViewController *controller;
        if (index == 0)
        {
            controller = [[BroadbandIPViewController alloc] init];
        }
        else if (index == 1)
        {
            controller = [[FixedIPViewController alloc] init];
        }
        else{
            controller = [[DynamicIPViewController alloc] init];
        }
        [vcs addObject:controller];
        [strongSelf.navigationController setViewControllers:vcs animated:NO];
    }];
    [self.wifiTypeView showInView:self.view];
}




- (IBAction)nextButtonClicked:(id)sender
{
    [self resignAllTextFiled];
    WEAKSELF
    [self.textArray enumerateObjectsUsingBlock:^(UITextField *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString *string = obj.text;
        NSLog(@"string:%@",string);
        if ([string checkEmpty])
        {
            if (idx == 0) {
             [self promptMessage:@"IP地址不能为空!"];
             return ;
            }
            if (idx == 1) {
                [self promptMessage:@"掩码不能为空!"];
                return;
            }
            if (idx == 2)
            {
                [self promptMessage:@"网关不能为空!"];
                return;
            }
            if (idx == 3)
            {
                [self promptMessage:@"DNS地址不能为空!"];
                return;
            }
            if (idx == 4)
            {
                [self promptMessage:@"备用地址不能为空!"];
                return;
            }
        }else
        {
            if (idx == 0) {
                strongSelf.ipAddress = string;
            }
            if (idx == 1) {
                strongSelf.maskCode = string;
            }
            if (idx == 2)
            {
                strongSelf.gateWay = string;
            }
            if (idx == 3)
            {
                strongSelf.DNS = string;
            }
            if (idx == 4)
            {
                strongSelf.DNSNote = string;
            }
        }
    }];

    
    self.activity = [self startActivityWithTitle:@"正在连接"];
    [self.discoverHelper checkIPConfigWithIPaddress:self.ipAddress mask:self.maskCode  gatewayaddr:self.gateWay dnsaddress:self.DNS dnsbakaddress:self.DNSNote success:^(BOOL succ, id responseObject, NSString *msg) {
        STRONGSELF
        [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
        [strongSelf checkInternetIsConnected];
    } failure:^(NSError *error) {
        NSString *failedReason = [error localizedDescription];
        [self stopActivityWithActivity:self.activity title:failedReason];
    }];
}




#pragma mark UITableView
-(UITableView *)tableView
{
    if (_tableView) {
        return _tableView;
    }
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    
    return _tableView;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
    }
    
    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UITextField *text = [cell.contentView addTextFieldWithDelegate:self fontSize:17];
    text.returnKeyType = UIReturnKeyNext;
    text.keyboardType = UIKeyboardTypeEmailAddress;
    text.tag = indexPath.row + 1;
    [text makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(5);
        make.bottom.offset(-5);
        make.left.offset(10);
        make.right.offset(-10);
    }];
    
    NSArray *place = @[@"IP地址", @"掩码", @"网关", @"DNS地址", @"备用DNS地址"];
    text.placeholder = [place objectAtIndex:indexPath.row];
    
    [self.textArray addObject:text];
    
    if (indexPath.row == 4) {
        text.returnKeyType = UIReturnKeyDone;
    }
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0f;
}

#pragma mark UITextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.tag == 5) {
        [textField resignFirstResponder];
    }else{
        UITextField *text = [self.textArray objectAtIndex:textField.tag];
        [text becomeFirstResponder];
    }
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)resignAllTextFiled
{
    [self.textArray enumerateObjectsUsingBlock:^(UITextField*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj resignFirstResponder];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/




- (void)checkInternetIsConnected
{
    WEAKSELF
    [self.discoverHelper discoverWIFISuccess:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObject:%@",responseObject);
        NSString *info = responseObject[@"info"];
        if ([info isEqualToString:@"InterNetConnected"])
        {
            [strongSelf promptMessage:@"网络连接正常!"];
            [self dispatchTimerWithTime:2.0 block:^{
                [strongSelf.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            NSString *type = responseObject[@"type"];
            if ([type isEqualToString:@"linkoff"])
            {
                [strongSelf promptMessage:@"网线没有插入WAN口!"];
            }
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString *failedReason = [error localizedDescription];
        [strongSelf promptMessage:failedReason];
    }];
}


#pragma mark -
#pragma mark   getters and setters
- (ChooseWIFITypeView *)wifiTypeView
{
    if (_wifiTypeView == nil)
    {
        _wifiTypeView = [ChooseWIFITypeView loadViewFromNib];
    }
    return _wifiTypeView;
}

@end
